package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;


//生成公共id
@Component
public class RedisIDWorker {
    //开始时间戳
    private static final long BEGIN_TIMESTAMP=1735689600;

    //序列号位数
    private static final int COUNT_BITS=32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIDWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextID(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowsecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp=nowsecond- BEGIN_TIMESTAMP;

        //2.生成序列号
        //获取当前日期
        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增长
        //使用redis自增
        Long count=stringRedisTemplate.opsForValue().increment("icr:"+keyPrefix+":"+data);

        //3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }

}
